/*
** collision.c for zomzom in /home/goupil_r//GameInLab/zomzom/src/goupil_r
**
** Made by robin goupil
** Login   <goupil_r@epitech.net>
**
** Started on  Sat Nov 17 15:30:37 2012 robin goupil
** Last update Sun Nov 18 16:21:34 2012 robin goupil
*/

#include <SDL/SDL.h>
#include <math.h>
#include "include/struct.h"
#include "include/player.h"
#include "include/zombie.h"
#include "include/world.h"
#include "include/utils.h"
#include "include/collision.h"
#include "include/my.h"

#define	PX	player->biped->pos.x
#define	PY	player->biped->pos.y
#define	ZX	zombie->biped->pos.x
#define	ZY	zombie->biped->pos.y
#define	RADIUS	(double)(player->biped->sprite->size + zombie->biped->sprite->size) / 2
#define BOUNCE	10

void		collision(t_world *world)
{
  t_player	*player;
  t_zombie	*zombie;
  double	x;
  double	y;

  player = world->player;
  zombie = world->zombie;
  while (zombie)
    {
      if (sqrt(((ZX - PX) * (ZX - PX)) + ((ZY - PY) * (ZY - PY))) < RADIUS)
	{
	  x = (ZX - PX) / RADIUS;
	  y = (ZY - PY) / RADIUS;
	  PX -= x + (player->biped->speed_x + zombie->biped->speed_x);
	  PY -= y + (player->biped->speed_y + zombie->biped->speed_y);
	  player->biped->speed_x *= x;
	  player->biped->speed_y *= y;
	  player->biped->speed_x = BOUNCE * -x;
	  player->biped->speed_y = BOUNCE * -y;
	}
      zombie = zombie->next;
    }
}

int		col_line_cercle(t_vec *a, t_vec *b, t_vec *c, double radius)
{
  t_vec		u;
  t_vec		v;
  t_vec		ac;
  double	num;
  double	den;

  u.x = b->x - a->x;
  u.y = b->y - a->y;
  ac.x = c->x - a->x;
  ac.y = c->y - a->y;
  den = (u.x * ac.y) - (u.y * ac.x);
  den = den < 0 ? den * -1 : den;
  num = sqrt((u.x * u.x) + (u.y * u.y));
  if (den / num < radius / 2)
    return (1);
  return (0);
}

int		col_seg_circle(t_vec *a, t_vec *b, t_vec *c, double radius)
{
  t_vec		u;
  t_vec		v;
  t_vec		ab;
  t_vec		bc;
  t_vec		ac;
  double	num;
  double	den;

  u.x = b->x - a->x;
  u.y = b->y - a->y;
  ac.x = c->x - a->x;
  ac.y = c->y - a->y;
  ab.x = b->x - a->x;
  ab.y = b->y - a->y;
  bc.x = c->x - b->x;
  bc.y = c->y - b->y;
  den = (u.x * ac.y) - (u.y * ac.x);
  den = den < 0 ? den * -1 : den;
  num = sqrt((u.x * u.x) + (u.y * u.y));
  if (den / num < radius / 2)
    {
      if (ab.x * ac.x + ab.y * ac.y >= 0 && (-ab.x) * bc.x + (-ab.y) * bc.y >= 0)
	return (1);
      if (sqrt(ac.x * ac.x + ac.y * ac.y) < radius / 2 ||
	  sqrt(bc.x * bc.x + bc.y * bc.y) < radius / 2)
	return (1);
    }
  return (0);
}
